var koa = require('koa');
var app = new koa();
var Router = require('koa-router');
var createLogger = require('concurrency-logger').default;
const koaBody = require('koa-body');
const config = require('./proxy-config.js');
const axios = require('axios');
const koaStatic = require('koa-static')
const send = require('koa-send')

var router = new Router();
const logger = createLogger({});

app.keys = ['some secret hurr'];
const proxyObj = {
  target: '',
  pathRewrite: {'': ''},
  headers:[]
}

router.all('*', async (ctx, next) => {
  var proxy = {}, url= '', custorm_headers={}
  for (let [key, value] of Object.entries(config)) {
    if(new RegExp(key).test(ctx.request.url)) {
      proxy = Object.assign({}, proxyObj, value)
      break
    }
  }
  if(Object.keys(proxy).length!=0) {
    let [replaceA,replaceB] = Object.entries(proxy.pathRewrite)[0]
    url = proxy.target + ctx.request.url.replace(replaceA, replaceB)
  }

  if(Object.keys(proxy).length!=0) {
    proxy.headers.forEach((item)=>{
      if(ctx.req.headers.hasOwnProperty(item)){
        custorm_headers[item] = ctx.req.headers.token
      }
    })
  }

  var options={
    url: url,
    method: ctx.req.method,
    headers: {
      cookie: ctx.req.headers.cookie ? ctx.req.headers.cookie:"",
      'content-type': ctx.req.headers['content-type'],
      'connection': ctx.req.headers['connection'],
      ...custorm_headers
    },
    params: ctx.request.params,
    data: ctx.request.body
  }

  options.responseType = 'stream'
  
  await axios(options).then((res) => {
    if(res.headers.hasOwnProperty('set-cookie')){
      ctx.response.set({"set-cookie":res.headers["set-cookie"]})
    }
    for(let prop in custorm_headers){
      if(res.headers.hasOwnProperty(prop)){
        ctx.response.set({[prop]: res.headers[prop]})
      }
    }
    ctx.response.set({"content-type":res.headers["content-type"]})
		ctx.body = res.data
  }).catch((err)=>{
    ctx.body = err.response.statusText
    ctx.status = err.response.status
  })
});

app
  .use(logger)
  .use(koaStatic('./static',{}))
  .use(koaBody())
  .use(router.routes())
  .use(router.allowedMethods())
  .listen(1000);

  console.log("server listen 1000");
